﻿$(document).ready(function() {
    $("#tree").bind("loaded.jstree", function(event, data) {
        $("#tree").jstree("open_all");
    });

    $("#tree").bind("refresh.jstree", function(event, data) {
        $("#tree").jstree("open_all");
    });

    $("#tree").bind("rename.jstree", function(e, data) {
        $.ajax({
            type: 'POST',
            url: '/Poll/RenameEntity',
            data: ({ entityID: data.rslt.obj.attr("id"), pollID: $("#pollID").val(), entityName: data.rslt.new_name }),
            cache: false,
            async: true
        });
    });

    $("#tree").bind("create.jstree", function(e, data) {
        $.ajax({
            type: 'POST',
            url: '/Poll/CreateEntity',
            data: ({ parentEntityID: data.rslt.parent.attr("id"), pollID: $("#pollID").val(), entityName: data.rslt.name }),
            cache: false,
            async: true,
            success: function(id) {
                data.rslt.obj.attr("id", id);
            }
        });
    });

    $("#tree").bind("move_node.jstree", function(e, data) {
        $.ajax({
            type: 'POST',
            url: '/Poll/MoveEntity',
            data: ({ entityID: data.rslt.o.attr("id"), newParentEntityID: data.rslt.np.attr("id"), pollID: $("#pollID").val(), copy: (data.rslt.cy ? "true" : "false") }),
            cache: false,
            async: true
        });
    });

    $("#tree").bind("remove.jstree", function(e, data) {
        $.ajax({
            type: 'POST',
            url: '/Poll/DeleteEntity',
            data: ({ entityID: data.rslt.obj.attr("id") }),
            cache: false,
            async: true
        });
    });

    $(function() {
        $("#tree").jstree({
            plugins: ["themes", "html_data", "ui", "crrm", "contextmenu", "dnd"],
            ui: { theme_name: "classic" },
            rules: {
                metadata: "mdata",
                use_inline: true,
                clickable: ["all"],
                deletable: ["all"],
                renameable: ["all"],
                creatable: ["all"],
                draggable: ["all"],
                //dragrules: ["child * child", "child inside root", "tree-drop inside root"],
                createat: ["top"],
                drag_button: "left",
                droppable: ["tree-drop"]
            }
        });

    });
});

